package com.wisezone.studentmanger.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentServlet1 extends HttpServlet {
	private Connection connection = null;

	@Override
	public void init(ServletConfig config) throws ServletException {
		// 1.加载数据库驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		// 2.建立连接
		try {
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentsystemdb", "root", "123");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("加载数据库驱动");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 3.操作数据
		String sql = "SELECT * FROM student";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = connection.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				int number = rs.getInt("number");
				String name = rs.getString("name");
				Timestamp time = rs.getTimestamp("datetime");

				System.out.println("学号:" + number + " 姓名:" + name + " 时间:" + time);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void destroy() {
		// 4.关闭数据连接
		try {
			if (connection != null)
				connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
